<template>
  <el-container>
    <el-header class="el-header"><el-button type="text" @click="goBack">&lt-首页</el-button> | {{ action }}</el-header>
    <el-main class="el-main">
    <el-button type="primary" @click="openVideo">打开摄像头</el-button>
    <el-button @click="closeVideo">关闭摄像头</el-button>
    <el-button type="danger" v-show="this.role === '学生'" @click="rec_Face" >开始识别</el-button>
    <el-button type="danger" v-show="this.role === '教师'" @click="clockIn" >上班打卡</el-button>
    <el-button type="danger" v-show="this.role === '教师'" @click="clockOff" >下班打卡</el-button>
    <div style="margin-top: 10px">
      <video id="video" ref="video" />
    </div>
    <canvas ref="canvas" width="400" height="300" style="display:none" />
    <!-- 截图展示图片 -->
    <img ref="screenshot">
    </el-main>
  </el-container>
</template>
<script>
import request from "@/utils/request";
import {ElMessage} from "element-plus";
import {click, faceRec} from "@/utils/api";
export default {
  name: "Face",
  data() {
    return {
      isCameraFlag: true,
      loading:false,
      action:""
    };
  },

  created() {
    this.role = sessionStorage.getItem("2")
    switch (this.role){
      case "学生":
        this.action = "门检识别";
        break
      case "教师":
        this.action = "打卡考勤";
        break
    }
  },
  methods: {
    goBack(){
      this.$router.push({path:"/main"})
    },
// 打开摄像头
    openVideo() {
      // 老的浏览器可能根本没有实现 mediaDevices，所以我们可以先设置一个空的对象
      console.log("navigator.mediaDevices", navigator.mediaDevices);
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      }
      // 一些浏览器部分支持 mediaDevices。我们不能直接给对象设置 getUserMedia
      // 因为这样可能会覆盖已有的属性。这里我们只会在没有getUserMedia属性的时候添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = constraints => {
          // 首先，如果有getUserMedia的话，就获得它
          const getUserMedia =
              navigator.getUserMedia ||
              (navigator.getUserMedia =
                  navigator.mozGetUserMedia ||
                  navigator.webkitGetUserMedia ||
                  navigator.msGetUserMedia);
          console.log("getUserMedia", getUserMedia);
          // 一些浏览器根本没实现它 - 那么就返回一个error到promise的reject来保持一个统一的接口
          if (!getUserMedia) {
            return Promise.reject(new Error("该浏览器暂不支持摄像头！"));
          }
          // 否则，为老的navigator.getUserMedia方法包裹一个Promise
          return new Promise((resolve, reject) => {
            getUserMedia.call(navigator, constraints, resolve, reject);
          });
        };
      }
      const constraints = {
        audio: false,
        video: {
          width: 800,
          height: 400
        }
      };
      console.log("window.navigator", window.navigator);
      window.navigator.mediaDevices
          .getUserMedia(constraints)
          .then(stream => {
            const video = this.$refs.video;
            // 旧的浏览器可能没有srcObject
            if ("srcObject" in video) {
              video.srcObject = stream;
            } else {
              // 防止在新的浏览器里使用它，因为它已经不再支持了
              video.src = window.URL.createObjectURL(stream);
            }
            video.onloadedmetadata = e => {
              video.play();
            };
          })
          .catch(err => {
            console.log(err.name + ": " + err.message);
          });
    },
    // 图片解析
    screenshot() {
      // 获取视频
      const video = this.$refs.video;
      // 获取截图的地址
      const screenshot = this.$refs.screenshot;
      // 获取canvas
      const canvas = this.$refs.canvas;
      // 渲染一个2d平面的视图
      const ctx = canvas.getContext("2d");
      // 设置canvas 视图文件地址和大小
      ctx.drawImage(video,0,0,400,250);
      // 将数据转为base64赋值给img标签的src属性
      screenshot.src = canvas.toDataURL("image/png");
      return {
        base64 : screenshot.src
      }
    },
    // 人脸识别
    rec_Face() {
      request.post("'/api/face'"+JSON.parse(sessionStorage.getItem("1")).id, {
        params: {
          base64: String(this.screenshot().base64),
        }
      })
      .then( res => {
        switch (res.code){
              case "0":
                ElMessage.success( '识别成功！')
                break
              case "1":
                ElMessage.error('识别失败！')
                break
        }
      }
      )
    },
    // 上班打卡
    clockIn() {

      this.form = JSON.parse(sessionStorage.getItem("1"))
      click("clockIn",this.form.id,String(this.screenshot().base64)).then( res => {
        switch (res.code){
          case "0":
            ElMessage.success( '打卡成功！')
            this.form.aid = res.data
            break
          case "1":
            ElMessage.error('打卡失败！')
            break
        }
      })
    },
    // 下班打卡
    clockOff() {
      request.put("/api/ter/clockOff/"+JSON.parse(sessionStorage.getItem("1")).id, {
        params: {
          base64: String(this.screenshot().base64),
        }
      }).then(res => {
        switch (res.code){
          case "0":
            ElMessage.success( '打卡成功！')
            break
          case "1":
            ElMessage.error('打卡失败！')
            break
        }
      })
    },
    // 关闭摄像头
    closeVideo() {
      console.log("srcObject", this.$refs.video.srcObject);
      const srcObject = this.$refs.video.srcObject ? this.$refs.video.srcObject.getTracks() : this.$refs.video.src.getTracks()
      srcObject.forEach(track => {
        track.stop();
        this.$refs.video.src = null;
      });
    },
  }
};
</script>

<style>
.el-header {
  height: 40px;
  line-height: 40px;
  font-size: 30px;
}
.el-main {
}
</style>